<template>
    <qly-select-popup ref="popupRef" @search="searchInput" @confirm="confirm" @cancel="emits('cancel')" :title="title"
                      :height="height" :search="search" :cancelText="cancelText" :confirmText="confirmText"
                      :cancelColor="cancelColor" :confirmColor="confirmColor">
        <view class="select-item" v-for="(item,index) in _options" :key="index"
              :style="valueIndexOf(item)?'color:'+selectColor+';':''"
              :class="{'select-item__disabled':item[customProps?.disabled]}" @tap="select(item)">
            <view class="title">{{ getLabelKeyValue(item) }}</view>
            <text v-if="valueIndexOf(item)" class="selectIcon icon-gou"/>
        </view>
    </qly-select-popup>
</template>

<script setup>
import config from '@/qly/ext/select'
import {isNotEmpty} from '@/qly/verificate'

const emits = defineEmits(['confirm', 'cancel', 'change'])
const props = defineProps({
    options: {type: Array, default: () => []},
    customProps: {type: Object, default: config.props},
    multiple: {type: Boolean, default: false},
    search: {type: Boolean, default: true},
    title: {type: String, default: ''},
    height: {type: [Number, String], default: '800rpx'},
    cancelText: {type: String, default: $t('common.cancel')},
    confirmText: {type: String, default: $t('common.confirm')},
    confirmAutoClose: {type: Boolean, default: true},
    selectColor: {type: String, default: "#409EFF"},
    cancelColor: {type: String, default: "#909399"},
    confirmColor: {type: String, default: "#3c9cff"},
    rightIconSize: {type: Number, default: 22},
    rightIconColor: {type: String, default: "#c0c4cc"}
})

const searchValue = ref('')
const popupRef = ref()
const selectList = ref([])
const selectValue = ref(null)
const _options = ref([])

// 监听options
watch(() => props.options, (newVal) => {
    setOptions(newVal, searchValue.value)
}, {deep: true, immediate: true})

// 搜索框值变化
function searchInput(e) {
    searchValue.value = e
    setOptions(props.options, e)
}

// 打开选择弹窗
function open(value) {
    // 重置搜索参数
    searchValue.value = ''
    setOptions(props.options, searchValue.value)
    if (props.multiple) {
        // 如果是多选，将value赋值给selectList
        if (isNotEmpty(value) && value instanceof Array) {
            selectList.value = qly.tool.deepCopy(value)
        } else {
            selectList.value = []
        }
    } else {
        // 如果是单选，将value赋值给selectValue
        selectValue.value = qly.tool.deepCopy(value)
    }
    popupRef.value.open()
}

// 设置选项
function setOptions(optionsData, searchData) {
    const copyOptions = []
    if (isNotEmpty(optionsData)) {
        for (const option of optionsData) {
            const label = getLabelKeyValue(option) + ''
            if (isNotEmpty(searchData) && label.indexOf(searchData) === -1) {
                continue
            }
            copyOptions.push(option)
        }
    }
    _options.value = copyOptions
}

// 点击选项
function select(item) {
    if (item[props.customProps.disabled]) {
        return
    }
    
    const val = getValueKeyValue(item)
    if (props.multiple) {
        // 多选
        const index = selectList.value.indexOf(val)
        if (index !== -1) {
            selectList.value.splice(index, 1)
        } else {
            selectList.value.push(val)
        }
    } else {
        // 单选
        if (selectValue.value == val) {
            selectValue.value = null
        } else {
            selectValue.value = val
        }
    }
    emits('change', val)
}

// 判断值是否被选中
function valueIndexOf(item) {
    const val = getValueKeyValue(item)
    if (props.multiple) {
        return selectList.value.indexOf(val) !== -1
    } else {
        return selectValue.value === val
    }
}

// 获取label
function getLabelKeyValue(item) {
    return item[props.customProps.label] ?? ''
}

// 获取value
function getValueKeyValue(item) {
    return item[props.customProps.value]
}

// 确认
function confirm() {
    let newValue
    if (props.multiple) {
        newValue = selectList.value
    } else if (isNotEmpty(props.options)) {
        newValue = selectValue.value
    } else {
        newValue = null
    }
    if (props.confirmAutoClose) {
        popupRef.value.close()
    }
    emits('confirm', qly.tool.deepCopy(newValue))
}

// 关闭弹窗
function close() {
    popupRef.value.close()
}

defineExpose({
    open,
    close
})
</script>

<style>
@font-face {
    font-family: "selectIcon";
    src: url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.eot?t=1590375117208'); /* IE9 */
    src: url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.eot?t=1590375117208#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAMEAAsAAAAABvQAAAK4AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDBgqBRIFCATYCJAMMCwgABCAFhQUHNRsfBsg+QCa3uoO0oAJTMwhxVu965keqWBy1hkbwtfzWb2Z279/shRhJisKF6FApKLI7oyBbpAaHo3w24k+ca9EUJbDmjaeznUdZ/FOUlkWdJ33rizZY/Pw6J5Xw0qKYxHTMesePHVT6EFpaC4zV70sKi2bYgNPc1w0WHnDVC/e/UnNTgyP+4Jq6BBpIHoisgypLaIAFEtU0wgeaIG8Yu4nAIZwnUK1QgFfOT6nUUoBpgXjj2lqplTMpiuXtCW3N2iK+aPTS2/Qdnzny8d+5IEiaDMy99exklra//FrKnX48pChmgrq5QcYRQCEe17ruqgqLAKv8WntwqwhpLms/nB5yW/iHRxJEC0QOgT3NnfgF01NBKvOuIzNoZdh5gJuAeGrsozE8vOJ7u5D832oz55039W5G+S52K0H+zNf1TJz07k26kqoQybRfwVFV4rjDS/K8EXUyuF1cXnT3weKS9Rvdm/xe7h8oA1hLwOR18R+Y4n4zwpr4z5SU089Vc+cpfWL+mn5APmT3Z39jeOs/GbWjK+DnmsuL/u6ehMX4j4yedSVkAUUuPh3TY022MtKZUEOtPqCb8Bkvnr5XT6imU0gGrEJW7aAL/gw0OhegVV2F6pC7uTOppirKIA4MFQhTrpCM+AbZlDu64L/QmAkQWlMhQXU75D07O9Gtl0PUYjTBLyAzOLNQYtypIEEjvsXtBLQTooV2nrQrGEau2gKmZlR4L8gwnGtBJbUn1diCOOQUnEkTkRAOeci9KHOQxvFro+tx3ZcGAaeljstCSBNDJuArgIyBYyy6OdZxAhHIELu1IC9AtgShCVtLltEKrSff1XoHJo3RC33hM63o3j6pSNkmqmIWEAtxFHB2OwoRBAfyeqE3r2ogHeF42dBhs7gvf7CukH5MmlUGOCpHihxFfs6TehDyKCqVAA==') format('woff2'),
    url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.woff?t=1590375117208') format('woff'),
    url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.ttf?t=1590375117208') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.svg?t=1590375117208#selectIcon') format('svg'); /* iOS 4.1- */
}

.selectIcon {
    position: absolute;
    right: 16rpx;
    font-family: "selectIcon" !important;
    font-size: 16px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.icon-gou:before {
    content: "\e61c";
}
</style>

<style scoped lang="scss">
.select-item {
    position: relative;
    line-height: 100rpx;
    display: flex;
}

.select-item.select-item__disabled {
    opacity: 0.5;
    cursor: default;
}

.select-item .title {
    flex: 1;
    font-size: 32rpx;
    text-align: center;
}

.text-blue {
    color: #909193;
}

.text-green {
    color: #3c9cff;
}
</style>
